<template>
  <div class="referral-management" style="padding: 20px; background: #f5f7fa; min-height: 100vh; width: 100%;">

    <!-- 顶部搜索区 -->
    <div style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 20px;">
      <div style="display: flex; gap: 20px; align-items: center; flex-wrap: wrap;">

        <div style="display: flex; align-items: center; gap: 8px;">
          <span style="font-size: 14px; color: #666;">患者姓名</span>
          <el-input v-model="search.patientName" placeholder="请输入" clearable size="small" style="width: 240px;" />
        </div>

        <div style="display: flex; align-items: center; gap: 8px;">
          <span style="font-size: 14px; color: #666;">转诊日期</span>
          <el-date-picker
            v-model="search.referralDateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            size="small"
            style="width: 240px;"
          />
        </div>

        <div style="display: flex; align-items: center; gap: 8px;">
          <span style="font-size: 14px; color: #666;">转诊状态</span>
          <el-select v-model="search.referralStatus" placeholder="全部" size="small" style="width: 120px;">
            <el-option label="全部" value="" />
            <el-option label="待接诊" value="待接诊" />
            <el-option label="已入院" value="已入院" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </div>

        <div>
          <el-button type="primary" size="small" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button size="small" @click="resetSearch">重置</el-button>
        </div>

      </div>
    </div>

    <!-- 主内容区 -->
    <div style="background: white; border-radius: 8px; padding: 30px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">

      <!-- 操作按钮 -->
      <div style="margin-bottom: 20px;">
        <el-button type="primary" size="small" @click="handleAddReferral">+ 转诊</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" stripe border style="width: 100%;"
        :header-cell-style="{ background: '#f8f9fa', color: '#333', fontSize: '14px' }"
        :cell-style="{ padding: '8px 12px', fontSize: '14px' }"
        row-key="id">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="patientName" label="患者姓名" min-width="120" />
        <el-table-column prop="inboundInstitution" label="转入机构" min-width="120" />
        <el-table-column prop="inboundDoctor" label="转入医生" min-width="120" />
        <el-table-column prop="referralApplyTime" label="转诊申请时间" width="160" />
        <el-table-column prop="referralType" label="转诊类型" width="100" />
        <el-table-column prop="referralStatus" label="转诊状态" width="100">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 8px;">
              <div 
                :style="{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: getStatusColor(row.referralStatus) }">
              </div>
              {{ row.referralStatus }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button 
              v-if="row.referralStatus === '待接诊'"
              type="primary" link size="small" @click="handleRevoke(row)">
              撤回
            </el-button>
            <el-button 
              v-else
              type="primary" link size="small" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.referralStatus === '已完成'"
              type="success" link size="small" @click="handleFollowUp(row)">
              随访
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="display: flex; justify-content: flex-end; padding: 12px 20px; font-size: 12px; color: #999; border-top: 1px solid #ebeef5;">
        <span style="margin-right: 15px;">总数：{{ pagination.total }} 条</span>
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 15, 20, 30]"
          layout="sizes, prev, pager, next, jumper"
          small
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

    </div>

    <!-- 新增转诊弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增转诊" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="患者姓名:" prop="patientName">
          <el-input v-model="formData.patientName" placeholder="请输入患者姓名" clearable />
        </el-form-item>
        <el-form-item label="转入机构:" prop="inboundInstitution">
          <el-input v-model="formData.inboundInstitution" placeholder="请输入转入机构" clearable />
        </el-form-item>
        <el-form-item label="转入医生:" prop="inboundDoctor">
          <el-input v-model="formData.inboundDoctor" placeholder="请输入转入医生" clearable />
        </el-form-item>
        <el-form-item label="转诊类型:" prop="referralType">
          <el-select v-model="formData.referralType" placeholder="请选择转诊类型" style="width: 100%;">
            <el-option label="门诊" value="门诊" />
            <el-option label="住院" value="住院" />
          </el-select>
        </el-form-item>
        <el-form-item label="转诊状态:" prop="referralStatus">
          <el-select v-model="formData.referralStatus" placeholder="请选择转诊状态" style="width: 100%;">
            <el-option label="待接诊" value="待接诊" />
            <el-option label="已入院" value="已入院" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据（纯前端存储，无接口依赖）
const tableData = ref([])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 15,
  total: 0
})

// 搜索条件
const search = reactive({
  patientName: '',
  referralDateRange: [],
  referralStatus: '',
  startDate: '',
  endDate: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const isEditing = ref(false)
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  patientName: '',
  inboundInstitution: '',
  inboundDoctor: '',
  referralApplyTime: new Date().toISOString().slice(0, 19).replace('T', ' '), // 当前时间
  referralType: '',
  referralStatus: '待接诊'
})

// 表单验证规则
const rules = {
  patientName: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
  inboundInstitution: [{ required: true, message: '请输入转入机构', trigger: 'blur' }],
  inboundDoctor: [{ required: true, message: '请输入转入医生', trigger: 'blur' }],
  referralType: [{ required: true, message: '请选择转诊类型', trigger: 'change' }],
  referralStatus: [{ required: true, message: '请选择转诊状态', trigger: 'change' }]
}

// 初始化模拟数据（纯前端测试用）
const initMockData = () => {
  const mockData = [
    {
      id: Date.now() - 30000,
      patientName: '张三',
      inboundInstitution: '市第一人民医院',
      inboundDoctor: '李医生',
      referralApplyTime: '2025-10-16 09:30:00',
      referralType: '门诊',
      referralStatus: '待接诊'
    },
    {
      id: Date.now() - 20000,
      patientName: '李四',
      inboundInstitution: '省中医院',
      inboundDoctor: '王医生',
      referralApplyTime: '2025-10-16 14:20:00',
      referralType: '住院',
      referralStatus: '已入院'
    },
    {
      id: Date.now() - 10000,
      patientName: '王五',
      inboundInstitution: '社区医院',
      inboundDoctor: '张医生',
      referralApplyTime: '2025-10-15 10:10:00',
      referralType: '门诊',
      referralStatus: '已完成'
    }
  ]
  tableData.value = mockData
  pagination.total = mockData.length
}

// 初始化加载模拟数据
onMounted(() => {
  initMockData()
})

// 状态颜色映射
const getStatusColor = (status) => {
  switch (status) {
    case '待接诊': return '#F56C6C' // 红色
    case '已入院': return '#67C23A' // 绿色
    case '已完成': return '#909399' // 灰色
    default: return '#909399'
  }
}

// 搜索（纯前端过滤数据）
const handleSearch = () => {
  // 处理日期范围
  if (search.referralDateRange && search.referralDateRange.length === 2) {
    search.startDate = search.referralDateRange[0]
    search.endDate = search.referralDateRange[1]
  } else {
    search.startDate = ''
    search.endDate = ''
  }

  // 前端过滤数据
  let filteredData = [...tableData.value]
  // 过滤患者姓名
  if (search.patientName) {
    filteredData = filteredData.filter(item => 
      item.patientName.includes(search.patientName)
    )
  }
  // 过滤转诊状态
  if (search.referralStatus) {
    filteredData = filteredData.filter(item => 
      item.referralStatus === search.referralStatus
    )
  }
  // 过滤日期范围
  if (search.startDate && search.endDate) {
    filteredData = filteredData.filter(item => {
      const applyDate = item.referralApplyTime.split(' ')[0]
      return applyDate >= search.startDate && applyDate <= search.endDate
    })
  }

  // 更新表格显示和分页总数
  tableData.value = filteredData
  pagination.total = filteredData.length
  pagination.currentPage = 1 // 搜索后重置到第一页
}

// 重置搜索
const resetSearch = () => {
  search.patientName = ''
  search.referralDateRange = []
  search.referralStatus = ''
  search.startDate = ''
  search.endDate = ''
  // 重置后显示全部数据
  initMockData()
  pagination.currentPage = 1
}

// 新增转诊
const handleAddReferral = () => {
  isEditing.value = false
  formData.id = null
  formData.patientName = ''
  formData.inboundInstitution = ''
  formData.inboundDoctor = ''
  formData.referralApplyTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
  formData.referralType = ''
  formData.referralStatus = '待接诊'
  dialogVisible.value = true
}

// 编辑转诊（纯前端编辑）
const handleEdit = (row) => {
  isEditing.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 保存表单（纯前端新增/编辑）
const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    ElMessage.success('保存成功')
    dialogVisible.value = false

    if (!isEditing.value) {
      // 新增：前端生成唯一ID（时间戳），拼接完整数据
      const newReferral = {
        id: Date.now(), // 时间戳作为唯一ID，避免重复
        ...formData
      }
      tableData.value.unshift(newReferral) // 添加到表格头部，即时显示
      pagination.total += 1 // 总数+1
    } else {
      // 编辑：更新表格中对应的数据
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        tableData.value[index] = { ...formData }
      }
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

// 撤回（纯前端移除数据）
const handleRevoke = (row) => {
  ElMessageBox.confirm(
    `确定撤回 "${row.patientName}" 的转诊？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 前端移除该条数据
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      pagination.total -= 1
      ElMessage.success('撤回成功')
    }
  }).catch(() => {
    ElMessage.info('已取消撤回')
  })
}

// 详情
const handleDetail = (row) => {
  ElMessage.info(`查看 ${row.patientName} 的详情：转入机构${row.inboundInstitution}，医生${row.inboundDoctor}`)
}

// 随访
const handleFollowUp = (row) => {
  ElMessage.success(`为 ${row.patientName} 创建随访计划成功`)
}

// 分页变化（纯前端分页）
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1 // 改变页大小时重置到第一页
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
}
</script>

<style scoped>
/* 状态圆点样式 */
.el-table__body tr td .cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>